package com.yueya.im.server.handler;

import com.yueya.im.common.api.CmdHandler;
import com.yueya.im.common.api.ImContext;
import com.yueya.im.common.api.RestMsgListener;
import com.yueya.im.common.constant.YueMsgCode;
import com.yueya.im.common.util.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 系统消息handler
 */
public class SystemMsgHandler implements CmdHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private RestMsgListener listener;

    @Override
    public boolean preMessage(int msgType, byte[] message, long msgId) {
        try {
            if (this.listener != null) {
                String text = new String(message, "utf-8");
                return this.listener.preMessage(text);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("发送系统消息异常", e);
            return false;
        }
        return true;
    }

    @Override
    public Serializable onMessage(ImContext ctx, int msgType, byte[] message, long msgId) {
        String msg = null;
        try {
            String text = new String(message, "utf-8");
            Map<String, Object> map = JsonMapper.getInstance().fromJson(text, Map.class);
            map.put("msgId", msgId);
            map.put("date", System.currentTimeMillis());
            msg = JsonMapper.toJsonString(map);
            Integer realMsgType = (Integer) map.get("msgType");
            String to = (String) map.get("to");
            switch (msgType) {
                case YueMsgCode.REST_MSG_POINT:
                    ctx.sendPointMsg(msgId, msg, realMsgType, to);
                    break;
                case YueMsgCode.REST_MSG_GROUP:
                    ctx.sendGroupMessage(msgId, msg, realMsgType, to);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            logger.error("发送系统消息异常", e);
        }
        return msg;
    }

    @Override
    public void postMessage(ImContext ctx, int msgType, byte[] message, long msgId, Serializable obj) {
        if (this.listener != null) {
            this.listener.postMessage((String) obj);
        }
    }

    public void setListener(RestMsgListener listener) {
        this.listener = listener;
    }
}
